var JobList = (function () {
    // instance
    var me = {};

    var ajaxURL = "/weixin/jobs";

    /**
     * 获取数据
     */
    me.get = function () {
        load_content();
    }

    // private variables
    /* 默认配置项 */
    var cfg = {
        wrapperId: "wrapper",
        scrollerId: "scroller",
        pullDownClass: "pullDown",
        pullDownLabelClass: "pullDownLabel",
        pullDownIconClass: "pullDownIcon",
        pullUpClass: "pullUp",
        pullUpIconClass: "pullUpIcon",
        pullUpLabelClass: "pullUpLabel"
    };

    var items_per_page = 10;
    var scroll_in_progress = false;
    var myScroll;
    var pullActionDetect = {
        count: 0,
        limit: 10,
        check: function (count) {
            if (count) {
                pullActionDetect.count = 0;
            }
            // Detects whether the momentum has stopped, and if it has reached the end - 200px of the scroller - it trigger the pullUpAction
            setTimeout(function () {
                if (myScroll.y <= (myScroll.maxScrollY + 200) && pullUpEl && !pullUpEl.className.match('loading')) {
                    $('.' + cfg.pullUpClass)
                        .addClass('loading')
                        .html('<span class="' + cfg.pullUpClass + '">&nbsp;</span><span class="' + cfg.pullUpLabelClass + '">加载中...</span>');
                    pullUpAction();
                } else if (pullActionDetect.count < pullActionDetect.limit) {
                    pullActionDetect.check();
                    pullActionDetect.count++;
                }
            }, 200);
        }
    };

    function render_data_to_ul(data) {
        $('#wrapper > #scroller > ul').append(data);
        $('div.row.job_item').wrap('<li>');
    }

    /**
     * Load content from server.
     */
    function load_content(refresh, next_page) {
//                console.log(refresh, next_page);
        if (!refresh) {
            // Loading the initial content

            $.get(ajaxURL, {page: 1}, render_data_to_ul);

        } else if (refresh && !next_page) {
            // Refreshing the content
            $.get(ajaxURL, {page: 1}, render_data_to_ul);
        } else if (refresh && next_page) {
            // Loading the next-page content and refreshing
            $.get(ajaxURL, {page: next_page}, render_data_to_ul);
        }

        if (refresh) {
            myScroll.refresh();
            pullActionCallback();
        } else {
            if (myScroll) {
                myScroll.destroy();
                $(myScroll.scroller).attr('style', ''); // Required since the styles applied by IScroll might conflict with transitions of parent layers.
                myScroll = null;
            }
            trigger_myScroll();
        }
    };

    /**
     * 处理下啦
     */
    function onPullDown() {
        load_content('refresh');
        $('#wrapper > #scroller > ul').data('page', 1);

        // Since "topOffset" is not supported with iscroll-5
        $('#wrapper > #scroller').css({top: 0});

    }

    /**
     * 处理上拉
     */
    function pullUpAction(callback) {
        if ($('#wrapper > #scroller > ul').data('page')) {
            var next_page = parseInt($('#wrapper > #scroller > ul').data('page'), 10) + 1;
        } else {
            var next_page = 2;
        }
        load_content('refresh', next_page);
        $('#wrapper > #scroller > ul').data('page', next_page);

        if (callback) {
            callback();
        }
    }

    /**
     * Pull 回调
     */
    function pullActionCallback() {
        if (pullDownEl && pullDownEl.className.match('loading')) {
            pullDownEl.className = cfg.pullDownClass;
            pullDownEl.querySelector('.' + cfg.pullDownLabelClass).innerHTML = '下拉刷新';
            myScroll.scrollTo(0, parseInt(pullUpOffset) * (-1), 200);
        } else if (pullUpEl && pullUpEl.className.match('loading')) {
            $('.' + cfg.pullUpClass).removeClass('loading').html('');
        }
    }

    function trigger_myScroll(offset) {
        var down_selector = '#' + cfg.wrapperId + ' .' + cfg.pullDownClass;
        var up_selector = '#' + cfg.wrapperId + ' .' + cfg.pullUpClass;
        pullDownEl = document.querySelector(down_selector);
        if (pullDownEl) {
            pullDownOffset = pullDownEl.offsetHeight;
        } else {
            pullDownOffset = 0;
        }
        pullUpEl = document.querySelector(up_selector);
        if (pullUpEl) {
            pullUpOffset = pullUpEl.offsetHeight;
        } else {
            pullUpOffset = 0;
        }

        if ($('#wrapper ul > li').length < items_per_page) {
            // If we have only 1 page of result - we hide the pullup and pulldown indicators.
            $('#wrapper .pullDown').hide();
            $('#wrapper .pullUp span').hide();
            offset = 0;
        } else if (!offset) {
            // If we have more than 1 page of results and offset is not manually defined - we set it to be the pullUpOffset.
            offset = pullUpOffset;
        }

        myScroll = new IScroll('#' + cfg.wrapperId, {
            probeType: 1,
            tap: true,
            click: false,
            preventDefaultException: {tagName: /.*/},
            mouseWheel: true,
            scrollbars: true,
            fadeScrollbars: true,
            interactiveScrollbars: false,
            keyBindings: false,
            deceleration: 0.0002,
            startY: (parseInt(offset) * (-1))
        });

        myScroll.on('scrollStart', function () {
            scroll_in_progress = true;
        });
        myScroll.on('scroll', function () {
            scroll_in_progress = true;
            var li_selector = '#' + cfg.wrapperId + ' ul > li';
            if ($(li_selector).length >= items_per_page) {
                if (this.y >= 5 && pullDownEl && !pullDownEl.className.match('flip')) {
                    pullDownEl.className = cfg.pullDownClass + ' flip';//'pullDown flip';
                    pullDownEl.querySelector('.' + cfg.pullDownLabelClass).innerHTML = '松开刷新';
                    this.minScrollY = 0;
                } else if (this.y <= 5 && pullDownEl && pullDownEl.className.match('flip')) {
                    pullDownEl.className = cfg.pullDownClass;
                    pullDownEl.querySelector('.' + cfg.pullDownLabelClass).innerHTML = '下拉刷新';
                    this.minScrollY = -pullDownOffset;
                }
                pullActionDetect.check(0);
            }
        });
        myScroll.on('scrollEnd', function () {
//                    console.log('scroll ended');
            setTimeout(function () {
                scroll_in_progress = false;
            }, 100);
            var selector = '#' + cfg.wrapperId + ' ul li';
            if ($(selector).length >= items_per_page) {
                if (pullDownEl && pullDownEl.className.match('flip')) {
                    pullDownEl.className = cfg.pullDownClass + ' loading';//'pullDown loading';
                    pullDownEl.querySelector('.' + cfg.pullDownLabelClass).innerHTML = '加载中...';
                    onPullDown();
                }
                // We let the momentum scroll finish, and if reached the end - loading the next page
                pullActionDetect.check(0);
            }
        });

        // In order to prevent seeing the "pull down to refresh" before the iScoll is trigger
        // the wrapper is located at left:-9999px and returned to left:0 after the iScoll is initiated
        setTimeout(function () {
            $('#' + cfg.wrapperId).css({left: 0});
        }, 100);
    }


    document.addEventListener('touchmove', function (e) {
        e.preventDefault();
    }, false);
    return me;
})()